// ./pages/HomePage.js
import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber ,Tooltip   } from 'antd';
import { startConversation } from '../../../api/device/mgt';
function DeviceMgt() {
    const [messages, setMessages] = useState([]); // 存储接收到的消息列表
    const [content, setContent] = useState('任务id为2'); // 存储接收到的消息列表
    const [shortMsg, setShortMsg] = useState(''); // 存储接收到的消息列表
    const [form] = Form.useForm();
    form.setFieldsValue({
        content,
    })
    useEffect(() => {
        const controller = new AbortController();
        const signal = controller.signal;
    
        const fetchWithSSE = async () => {
          try {
            const response = await fetch('https://api.coze.cn/v3/chat', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json;charset=utf-8',
                'Authorization': 'Bearer pat_4xhyXJf8RC9PGcUjsfg8eAwabOMrK0I3dYBvAEVsmp5KEYxKn3jbkQUq385VwndC'
              },
              body: JSON.stringify({
                bot_id: "7391702868350844969",
                user_id: "123123",
                stream: true,
                auto_save_history: true,
                additional_messages: [
                  {
                    role: "user",
                    content: content,
                    content_type: "text"
                  }
                ]
              }),
              signal: signal // 使用AbortController来控制请求的取消
            });
    
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
    
            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
    
            while (true) {
              const { done, value } = await reader.read();
              if (done) break;
              const chunk = decoder.decode(value, { stream: true });
              console.log(chunk); // 或者在这里处理接收到的数据
              // 对每个事件进行解析和处理
              const lines = chunk.split('\n');
              let flg = false;
              let shortFlg = false;
              for (let line of lines) {
                if(line.startsWith('event:')) {
                  const eventSse = line.substring(6);
                  //console.log('=====sse e====',eventSse);
                  if(eventSse==='conversation.message.completed') {
                      flg = true;
                  }
                  if(eventSse==='conversation.message.delta') {
                      shortFlg = true;
                  }
                }
                if (line.startsWith('data:') && flg) {
                  const data = JSON.parse(line.substring(5));
                  //console.log(data);
                  if(data.role==='assistant' && data.type==='answer') {
                    setMessages(prevMessages => [...prevMessages, data.content]);
                    flg = false;
                  }
                  // 在这里处理每个数据块
                }
                if (line.startsWith('data:') && shortFlg) {
                    const data = JSON.parse(line.substring(5));
                    //console.log(data);
                    if(data.role==='assistant' && data.type==='answer') {
                      setShortMsg(prevMessages => [...prevMessages, data.content]);
                      shortFlg = false;
                    }
                    // 在这里处理每个数据块
                  }
              }
            }
          } catch (error) {
            console.error('Fetch error:', error);
          }
        };
    
        fetchWithSSE();
    
        return () => {
          controller.abort(); // 当组件卸载时取消请求
        };
      }, [content]);

      const onFinish = async (values) => {
        const { content } = values;
        setShortMsg('');
        setMessages([]);
        setContent(content);
      }
  
    return (
      <div>
        <h3>接收消息</h3>
        <Form form={form} layout="inline" onFinish={onFinish}>
          <Form.Item label="对话内容：" name="content">
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType='submit'>发送</Button>
          </Form.Item>
        </Form>
        <div>{shortMsg}</div>
        {/* <ul>
          {messages.map((msg, index) => (
            <li key={index}>{msg}</li>
          ))}
        </ul> */}
      </div>
    );
  };
export default DeviceMgt;